package org.glut.cloud.userManage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.glut.cloud.userManage.entity.AdminUsers;
import org.glut.cloud.userManage.service.EmailService;
import org.glut.cloud.userManage.service.IAdminUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 管理员用户表 前端控制器
 *
 * @author Venus
 * @since 2024-08-13 11:45
 */
@RestController
@RequestMapping("/admin-users")
public class AdminUsersController {

    @Autowired
    private IAdminUsersService adminUsersService;

    @Autowired
    private EmailService emailService;

    private Map<String, String> verificationCodes = new HashMap<>();
    private Map<String, Long> verificationCodeTimes = new HashMap<>(); // 存储验证码发送时间

    // 登录功能的实现
    @PostMapping("/login")
    public Map<String, String> login(@RequestBody AdminUsers loginRequest) {
        AdminUsers user = adminUsersService.getOne(new QueryWrapper<AdminUsers>().eq("username", loginRequest.getUsername()));
        Map<String, String> response = new HashMap<>();
        if (user == null) {
            response.put("message", "用户不存在");
            return response;
        }
        if (!user.getPassword().equals(loginRequest.getPassword())) {
            response.put("message", "密码错误");
            return response;
        }
        response.put("message", "登录成功");
        return response;
    }

    // 注册功能的实现
    @PostMapping("/register")
    public Map<String, String> register(@RequestBody AdminUsers adminUser) {
        Map<String, String> response = new HashMap<>();
        boolean exists = adminUsersService.getOne(new QueryWrapper<AdminUsers>().eq("username", adminUser.getUsername())) != null;
        if (exists) {
            response.put("message", "用户名已存在");
            return response;
        }
        adminUser.setCreateTime(new Date());
        adminUser.setUpdateTime(new Date());
        boolean success = adminUsersService.save(adminUser);
        if (success) {
            response.put("message", "注册成功");
        } else {
            response.put("message", "注册失败");
        }
        return response;
    }

    // 发送验证码功能的实现
    @PostMapping("/forgot-password")
    public Map<String, String> forgotPassword(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String email = request.get("email");

        AdminUsers user = adminUsersService.getOne(new QueryWrapper<AdminUsers>().eq("username", username).eq("email", email));
        Map<String, String> response = new HashMap<>();
        if (user == null) {
            response.put("message", "用户不存在或邮箱不匹配");
            return response;
        }

        String code = String.valueOf(new Random().nextInt(899999) + 100000);
        verificationCodes.put(username, code);
        verificationCodeTimes.put(username, System.currentTimeMillis()); // 存储验证码发送时间
        boolean emailSent = emailService.sendResetPasswordEmail(email, code);

        if (emailSent) {
            response.put("message", "验证码已发送到您的邮箱");
        } else {
            response.put("message", "验证码发送失败，请稍后重试");
        }
        return response;
    }

    // 验证验证码功能的实现
    @PostMapping("/verify-code")
    public Map<String, String> verifyCode(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String code = request.get("code");

        Map<String, String> response = new HashMap<>();
        String storedCode = verificationCodes.get(username);
        Long sendTime = verificationCodeTimes.get(username);

        if (storedCode != null && storedCode.equals(code)) {
            if (System.currentTimeMillis() - sendTime < 5 * 60 * 1000) { // 验证码有效期为5分钟
                response.put("message", "验证成功");
                verificationCodes.remove(username); // 验证成功后删除验证码
                verificationCodeTimes.remove(username); // 删除对应的发送时间
            } else {
                response.put("message", "验证码已过期");
            }
        } else {
            response.put("message", "验证码错误或已过期");
        }
        return response;
    }

    // 重置密码功能的实现
    @PostMapping("/reset-password")
    public Map<String, String> resetPassword(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String newPassword = request.get("newPassword");

        Map<String, String> response = new HashMap<>();
        AdminUsers user = adminUsersService.getOne(new QueryWrapper<AdminUsers>().eq("username", username));

        if (user != null) {
            user.setPassword(newPassword);
            user.setUpdateTime(new Date());
            adminUsersService.updateById(user);
            response.put("message", "重置成功");
        } else {
            response.put("message", "用户不存在");
        }
        return response;
    }

    @GetMapping("/{id}")
    public AdminUsers getAdminUserById(@PathVariable Integer id) {
        return adminUsersService.getById(id);
    }

    @GetMapping
    public List<AdminUsers> getAllAdminUsers() {
        return adminUsersService.list();
    }

    @GetMapping("/username/{username}")
    public AdminUsers getAdminUserByUsername(@PathVariable String username) {
        return adminUsersService.getOne(new QueryWrapper<AdminUsers>().eq("username", username));
    }

    // 更新用户信息功能的实现
    @PutMapping("/update")
    public Map<String, String> updateUser(@RequestBody AdminUsers adminUser) {
        Map<String, String> response = new HashMap<>();
        boolean success = adminUsersService.updateById(adminUser);
        if (success) {
            response.put("message", "更新成功");
        } else {
            response.put("message", "更新失败");
        }
        return response;
    }
}
